﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using NopSolutions.NopCommerce.BusinessLogic;
using NopSolutions.NopCommerce.BusinessLogic.CustomerManagement;
using NopSolutions.NopCommerce.BusinessLogic.Orders;
using NopSolutions.NopCommerce.BusinessLogic.Payment;
using NopSolutions.NopCommerce.BusinessLogic.Products;
using NopSolutions.NopCommerce.BusinessLogic.Profile;
using NopSolutions.NopCommerce.BusinessLogic.SEO;
using NopSolutions.NopCommerce.Common.Utils;
using NopSolutions.NopCommerce.BusinessLogic.Infrastructure;

namespace NopSolutions.NopCommerce.Web
{
    public partial class OrderTracking : BaseNopFrontendPage
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
              if ((!string.IsNullOrEmpty(Request.QueryString["email"])) && (!string.IsNullOrEmpty(Request.QueryString["ordernumber"])))
              {
                tbEmail.Text = HttpUtility.UrlDecode(Request.QueryString["email"]);
                tbOrderNumber.Text = HttpUtility.UrlDecode(Request.QueryString["ordernumber"]);

                btnRequest_Click(this, new EventArgs());
              }
              else
              {
                pnlTrackingParams.Visible = true;
                pnlTrackingInfo.Visible = false;
              }
            }
        }

        void TrackOrder(int orderNumber, string email)
        {
            Customer customer = CustomerService.GetCustomerByEmail(email);
            if (customer == null)
            {
                lbInfo.Text = "Заказ не найден";
                lbInfo.ForeColor = System.Drawing.Color.Red;
                return;
            }

            Order order = OrderService.GetOrderById(orderNumber);
            if (order == null || order.CustomerId != customer.CustomerId)
            {
                lbInfo.Text = "Заказ не найден";
                lbInfo.ForeColor = System.Drawing.Color.Red;
                return;
            }

            lbInfo.Text = "Статус Вашего заказа: " + order.OrderStatus.GetOrderStatusName();

            gvOrderNotes.DataSource = order.OrderNotes.Where(o => o.DisplayToCustomer).ToList();
            gvOrderNotes.DataBind();
        }

        protected void btnRequest_Click(object sender, EventArgs e)
        {
            pnlTrackingInfo.Visible = true;
            pnlTrackingParams.Visible = false;
            int orderNumber = 0;
            
            if (!int.TryParse(tbOrderNumber.Text, out orderNumber))
            {
                lbInfo.Text = "Заказ не найден";
                lbInfo.ForeColor = System.Drawing.Color.Red;
                return;
            }

            TrackOrder(orderNumber, tbEmail.Text);
        }
    }
}